package com.xq.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xq.dao.TbUserDao;
import com.xq.entity.TbUser;
import com.xq.jwt.JwtToken;
import com.xq.pwdmd5.MD5Utils;
import com.xq.response.Result02;
import com.xq.service.TbUserService;
import com.xq.vo.TbUserVo;
import com.xq.vo.TbloadUserVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户表(TbUser)表服务实现类
 *
 * @author makejava
 * @since 2020-07-19 16:19:23
 */
@Service("tbUserService")
public class TbUserServiceImpl extends ServiceImpl<TbUserDao, TbUser> implements TbUserService {
    @Resource
    private TbUserDao tbUserDao;

    /**
     * 带条件的分页查询
     *
     * @param current
     * @param size
     * @param userVo
     * @return
     */
    @Override
    public Page<TbUser> findByPageOrTbUserVo(Integer current, Integer size, TbUserVo userVo) {
        //创建分页对象
        Page<TbUser> page = new Page<>(current, size);
        //创建条件迭代器
        QueryWrapper wrapper = new QueryWrapper();
        System.out.println("====" + userVo);
        //防止空指针异常
        if (userVo != null) {
            //用户名
            if (userVo.getUsername() != null && !userVo.getUsername().equals("")) {
                wrapper.like("username", userVo.getUsername());
            }
            //邮箱
            if (userVo.getEmail() != null && !userVo.getEmail().equals("")) {
                wrapper.like("email", userVo.getEmail());
            }
            //性别 3表示无性别要求
            if (userVo.getSex() != null && userVo.getSex() != 3) {
                wrapper.eq("sex", userVo.getSex());
            }
            //昵称
            if (userVo.getNickname() != null && !userVo.getNickname().equals("")) {
                wrapper.like("nickname", userVo.getNickname());
            }
            //所属部门
            if (userVo.getDepartmentId() != null) {
                wrapper.eq("department_id", userVo.getDepartmentId());
            }
        }
        //逻辑删除 自定义的sql 需自己指定逻辑删除
        wrapper.eq("deleted", 0);
        //page.setRecords(tbUserDao.selectPage(Page));
        //返回分页对象
        Page pages = tbUserDao.findByPageByDep(page, wrapper);
        return pages;
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public String loginUser(String username, String password) {
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("username", username);
        //用于拿取盐值
        TbUser tbUser = tbUserDao.selectOne(wrapper1);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", username);

        wrapper.eq("password", MD5Utils.md5Encryption(password, tbUser.getSalt()));
        TbUser tbUsers = tbUserDao.selectOne(wrapper);
        JwtToken jwtToken=new JwtToken();
        String token = jwtToken.createJwt(tbUsers.getUsername(), tbUsers.getId().toString());
        return token;
    }

    /**
     * 增加操作
     *
     * @param user
     */
    @Override
    public Integer instUser(TbUser user) {
        String salt = UUID.randomUUID().toString().substring(0, 32);
        //状态
        user.setStatus(1);
        //加密 盐
        user.setSalt(salt);
        //密码加密
        user.setPassword(MD5Utils.md5Encryption(user.getPassword(), salt));
        //默认系统用户 1
        user.setType(1);
        return tbUserDao.insert(user);
    }

    /**
     * 禁用操作
     *
     * @param id
     * @param status
     */
    @Override
    public Boolean updStatusById(Integer id, Integer status) {
        Boolean update = tbUserDao.updStatusById(id, status);
        return update;
    }

    /**
     * 导出信息
     *
     * @param response
     */
    @Override
    public void download(HttpServletResponse response, TbUserVo tbUserVo) throws IOException {
        QueryWrapper queryWrapper = new QueryWrapper(tbUserVo);
        if (!StringUtils.isEmpty(tbUserVo.getUsername())) {
            queryWrapper.like("username", tbUserVo.getUsername());
        }
        //邮箱
        if (!StringUtils.isEmpty(tbUserVo.getEmail())) {
            queryWrapper.like("email", tbUserVo.getEmail());
        }
        //性别 3表示无性别要求
        if (!StringUtils.isEmpty(tbUserVo.getSex()) && tbUserVo.getSex() != 3) {
            queryWrapper.eq("sex", tbUserVo.getSex());
        }
        //昵称
        if (!StringUtils.isEmpty(tbUserVo.getNickname())) {
            queryWrapper.like("nickname", tbUserVo.getNickname());
        }
        //所属部门
        if (!StringUtils.isEmpty(tbUserVo.getDepartmentId())) {
            queryWrapper.eq("department_id", tbUserVo.getDepartmentId());
        }

        //逻辑删除 自定义的sql 需自己指定逻辑删除
        queryWrapper.eq("deleted", 0);
        //返回分页对象
        List<TbloadUserVo> tbUsers = tbUserDao.findAllDownload(queryWrapper);
        response.setContentType("application/vnd.ms-excel");
        //swagger2 防止打不开
        response.setHeader("Content-disposition", "attachment;filename=datax.xlsx");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("users", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), TbUserVo.class).sheet("模板").doWrite(tbUsers);
    }

}